import common from '../utils/common';
import userHelper from '../utils/userHelper';
import loginOperation from '../utils/loginOperation';
/*import jsApi from '../utils/cx580.jsApi';*/

require('isomorphic-fetch');

class ApiHelper {

    isTMall = window.location.href.indexOf('jaeapp.com') > -1 ? true : false;//是否为天猫渠道，天猫渠道直接跨域访问cx580
    production = this.isTMall || window.location.href.indexOf('https://annualcheck.cx580.com/') > -1 || window.location.href.indexOf('https://pre.cx580.com:58083') > -1 ? true : false; //是否为生产环境
    /**
     * 切换本地，生产或测试环境
     * 本地统一走http://192.168.1.165:7083/
     */

    baseApiUrl = location.hostname == "localhost" || location.hostname == "local-test.cx580.com" ? "http://192.168.1.165:7083/" : (this.isTMall ? 'https://annualcheck.cx580.com/' : (location.protocol + "//" + location.host + "/"));//  192.168.2.225
    // wxApiUrl = this.production ? "https://webservice.cx580.com/" : location.hostname=="localhost"?"http://192.168.1.165:9071/":"http://"+location.host+"/";//  192.168.2.225


    /**
     * 获取 HTTP 头
     */
    _getHeaders() {
        return {
            "Accept": "*/*",
            // "authorization": "Basic Y3h5aW06Y3g1ODBjeDU4MGN4NTgws",
        }
    }

    /**
     * 封装fetch
     */
    fetch(requestParam) {
        let setTimeNum = 250; //默认延迟250毫秒请求数据 兼容APP处理

        let UserIdAndToken = userHelper.getUserIdAndToken(); //先去获取用户数据，避免数据没有实时返回

        let promise = new Promise((resolve, reject) => {
            setTimeout(() => {
                // console.log("requestParam", requestParam);
                requestParam.data.method = requestParam.data.method || "get";
                requestParam.data.headers = requestParam.data.headers || {};
                Object.assign(requestParam.data.headers, this._getHeaders());
                if (requestParam.data.method.trim().toLowerCase() == "post") {
                    requestParam.data.headers["Content-Type"] = "application/x-www-form-urlencoded";
                }
                requestParam.data.body = requestParam.data.body || {};

                UserIdAndToken = userHelper.getUserIdAndToken();
                if (!requestParam.data.body.userId) {
                    requestParam.data.body["userId"] = UserIdAndToken.userId;
                }
                if (!requestParam.data.body.token) {
                    requestParam.data.body["token"] = UserIdAndToken.token;
                }

                if (!requestParam.data.body.userType) {
                    requestParam.data.body["userType"] = UserIdAndToken.userType;
                }
                if (!requestParam.data.body.openId) {
                    requestParam.data.body["openId"] = UserIdAndToken.openId;
                }

                if (UserIdAndToken.deviceId && !requestParam.data.body.deviceId) {
                    requestParam.data.body["deviceId"] = UserIdAndToken.deviceId;
                }
                //增加通用公共参数，识别不同入口
                if (!requestParam.data.body.visitChannel) {
                    let detailUserType = UserIdAndToken.detailUserType;
                    requestParam.data.body["visitChannel"] = detailUserType;
                }
                //请求时将版本号传给后端,upload接口为其他服务器接口，自定义http头会报错，故略去
                if (requestParam.url.indexOf('alqc2017') < 0 && requestParam.url.indexOf('upload') < 0 && !requestParam.data.headers.tVersion) {
                    requestParam.data.headers["tVersion"] = '1.6';
                }

                //保存用户信息及城市信息(用于判断是否需要刷新页面重新获取信息)
                localStorage.setItem("g_userId", UserIdAndToken.userId);
                localStorage.setItem("g_userToken", UserIdAndToken.token);
                localStorage.setItem("g_city", UserIdAndToken.city);

                requestParam.data.body = common.toQueryString(requestParam.data.body);


                requestParam.data.mode = "cors";
                if (requestParam.data.method.trim().toLowerCase() == "get") {
                    var request = new Request(requestParam.url + '?' + requestParam.data.body); //get请求不能有body,否则会报错
                } else {
                    var request = new Request(requestParam.url, requestParam.data);
                }
                let result = window.fetch(request, {headers: requestParam.data.headers})
                    .then(function (response) {
                        let resp = response.json();
                        resp.then(function (data) {
                            if (data.code == "4222") {
                                //app模式下进行检测到未登录状态时进行登录
                                if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
                                    loginOperation.appLoginWithoutCheck(() => {
                                        window.location.reload();
                                    });
                                    return;
                                }
                                else {
                                }
                            }
                        });
                        return resp;
                    })
                    .catch(function (e) {
                        if (window.location.href.indexOf('test.cx580.com/') >= 0) {
                            alert(requestParam.url);
                            alert(sessionStorage.getItem("userId"));
                            alert(sessionStorage.getItem("token"));
                            alert(JSON.stringify(e));
                        }
                        console.error("fetch 请求出错了");
                        console.dir(e);
                        throw e;
                    });
                //console.log("result", result);
                resolve(result)

            }, setTimeNum);

            // 网络超时
            setTimeout(() => reject('网络错误'), 30000);
        });

        return promise;
    }
}

// 实例化后再导出
export default new ApiHelper()